package cn.ybz21.hibot.topic_process_center.app;

import java.io.IOException;
import java.lang.reflect.Field;

import cn.ybz21.hibot.bean.App;
import cn.ybz21.hibot.bean.AppState;
import cn.ybz21.hibot.db.service.AppDAO;
import cn.ybz21.hibot.topic_process_center.base.BaseCenter;
import cn.ybz21.hibot.util.FileUtil;
import cn.ybz21.hibot.util.StaticValues;
import cn.ybz21.hibot.util.shell.ShellExecutor;
import cn.ybz21.hibot.util.shell.SudoExecutor;

import com.google.gson.Gson;
import com.ibm.micro.client.mqttv3.MqttMessage;
import com.ibm.micro.client.mqttv3.MqttTopic;

public class AppStartCenter implements BaseCenter {
	long pid ;
	@Override
	public void doAction(MqttTopic topic, MqttMessage message) {
		System.out.println("---------------------\nstart app");
		System.out.println(message.toString());
		Gson gson = new Gson();
		App app = (App) gson.fromJson(message.toString(), App.class);
		start(app);
		System.out.println("end start app\n---------------------");
	}

	void start(App app) {
		genShells(app);
		runShells(app);
		saveIntoDB(app);
	}
	void saveIntoDB(App app){
		app.pid=pid+"";
		app.state=AppState.RUNNING;
		new AppDAO().updateAppState(app);
	}

	public static void main(String args[]) {
		App app = new App();
		app.name = "mergelaunch";
		app.startCmd = "roslaunch gmapping my.launch ";
		AppStartCenter test = new AppStartCenter();
		test.start(app);
	}

	private void genShells(App app) {
		String str = "#!/bin/bash";
		String str1 = "cd " + StaticValues.PATH_ROS;
		String str2 = "catkin_make";
		String str3 = "source ./devel/setup.bash";
		String str4 = app.startCmd;
		String strs[] = { str, str1, str2, str3, str4 };
		FileUtil.writeFile(strs, StaticValues.PATH_SHELL, app.name + ".sh");
	}

	private void runShells(App app) {
		SudoExecutor exe = new SudoExecutor();
		try {
			exe.chmod(StaticValues.PATH_ROS_SRC);
			exe.chmod(StaticValues.PATH_SHELL + "/" + app.name + ".sh");
		} catch (IOException | InterruptedException e) {
			e.printStackTrace();
			System.err.println("error in add chmod");
		}
		Process process = ShellExecutor.execLocal("sh "
				+ StaticValues.PATH_SHELL + "/" + app.name + ".sh",false);
		try {
			Class<?> clazz = Class.forName("java.lang.UNIXProcess");
			Field field = clazz.getDeclaredField("pid");
			field.setAccessible(true);
			 pid = (Integer) field.get(process);
			System.out.println("pid:" + pid);
		} catch (Exception e) {
			e.printStackTrace();
		}

		AppStorage.addAppProcess(app.id, process);
//		for(int i=0;i<10;i++)
//			try {
//				System.out.println("sleep "+i);
//				Thread.sleep(1000);
//			} catch (InterruptedException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//		process.destroy();
//		process.destroyForcibly();
	}

}
